#include "sql.h"
#include <mysql.h>
#include <stdlib.h>
#include "../Tuple.h"
#include "../Database.h"
#include "../../Defines.h"
#include "../../Tools/linked_list.h"
#include <string.h>
#include <stdio.h>

static const char* const Server = "localhost"; // CHANGE THIS B4 UPLOADING "localhost"
static const char* const User = "root";
static const char* const Password = "Spring2012";
static const char* const Database = "canoodle";

// destroys input tuple, returns list of results
node_t* readData(tuple_t* matchingVals)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    node_t* result = NULL;
    node_t* head = init_list(NULL);
    tuple_t* temp = NULL;
    char query[1000];
    //char* buffer;
    unsigned int numFields;
    unsigned long* lengths;
    int i = 0;
    int i2 = 0;
    int firstAttr = 1;


    // TODO: build this string manually instead of with strcat.
    // should be more efficient.
    strcpy(query, "select ");
    numFields = getNumParams(matchingVals->table);
    for(i = 0; i < numFields - 1; i++)
    {
        strcat(query, TableAttributes[matchingVals->table][i]);
        strcat(query, ", ");
    }
    strcat(query, TableAttributes[matchingVals->table][i]);

    strcat(query, " from ");
    strcat(query, TableNames[matchingVals->table]);

    strcat(query, " where ");

    for(i = 0; i < numFields; i++)
    {
        if(matchingVals->params[i])
        {
            if(firstAttr)
            {
                firstAttr = 0;
            }
            else
            {
                strcat(query, " AND ");
            }
            strcat(query, TableAttributes[matchingVals->table][i]);
            strcat(query, " = \"");
            strcat(query, (char*)(matchingVals->params[i]));
            strcat(query, "\"");
            
        }
    }

    conn = mysql_init(NULL);
    /* Connect to database */
    if (!mysql_real_connect(conn, Server,
        User, Password, Database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
    }

    /* send SQL query */
    if (mysql_query(conn, query)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
    }
    res = mysql_use_result(conn);

    // get results
    result = head;
    while ((row = mysql_fetch_row(res)) != NULL)
    {
        temp = initTuple(matchingVals->table);

        lengths = mysql_fetch_lengths(res);
        for(i = 0; i < numFields; i++)
        {
            if(row[i])
            {
                // assumes all values are returned as strings...
                // based on testing this seems to be the case.
                temp->params[i] = (char*)malloc(sizeof(char) * (lengths[i] + 1)); // null-term
                for(i2 = 0; i2 < lengths[i]; i2++)
                {
                    ((char*)(temp->params[i]))[i2] = ((char*)(row[i]))[i2];
                }
                ((char*)(temp->params[i]))[i2] = 0;
            }
            else
            {
                temp->params[i] = NULL;
            }
        }

        result = insert_node(result, temp);
    }

    /* close connection */
    mysql_free_result(res);
    mysql_close(conn);

    result = head->next;
    free(head);

    return result;
}

result_type insertData(tuple_t* values)
{
    MYSQL *conn;
    MYSQL_RES *res;
    result_type result = SUCCESS;
    //char *server = "localhost";
    char query[1000];
    int i, numFields;

    //TODO: build query w/o strcats
    strcpy(query, "replace into ");
    strcat(query, TableNames[values->table]);
    strcat(query, "(");

    numFields = getNumParams(values->table);
    for(i = 0; i < (numFields - 1); i++)
    {
        strcat(query, TableAttributes[values->table][i]);
        strcat(query, ", ");
    }
    strcat(query, TableAttributes[values->table][i]);
    strcat(query, ")");

    strcat(query, " values(\"");
    // assuming all values are valid....
    for(i = 0; i < (numFields - 1); i++)
    {
        strcat(query, (char*)(values->params[i]));
        strcat(query, "\", \"");
    }
    strcat(query, (char*)(values->params[i]));
    strcat(query, "\")");

    conn = mysql_init(NULL);
    /* Connect to database */
    if (!mysql_real_connect(conn, Server,
         User, Password, Database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        result = GENERAL_ERROR;
    }

    /* send SQL query */
    if (mysql_query(conn, query)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        result = GENERAL_ERROR;
    }
    res = mysql_use_result(conn);

    /* close connection */
    mysql_free_result(res);
    mysql_close(conn);

    return result;
}
